<?php

class HrUsersTable extends Doctrine_Table
{


    public function findUserByUsername($username) {
        $q = $this->addActiveUsersQuery();
        $q->andWhere("user_name = ?", $username)
            //->andWhere("acct_set_id = ?", Doctrine::getTable("AcctSet")->getCurrentSet()->getId());
            ->andWhere("acct_set_id = ?", sfContext::getInstance()->getUser()->getAttribute("acct_set"));

           
        return $q->fetchOne();

    }

    public function addActiveUsersQuery(Doctrine_Query $q = null) {

        if(is_null($q)) {
            $q = Doctrine_Query::create()
                        ->from("HrUsers");
        }
        $q->addWhere("is_activated = ?", 1);

        return $q;
    }

    public function getUserCredentials($user_id = null) {

        if(empty($user_id)) {
            $user_id = sfContext::getInstance()->getUser()->getAttribute("user_id");
        }
        //get user roles
        //echo "get user roles";
        $credentials = array();
        $user_roles = Doctrine::getTable("SysUserRole")->getUserRoles($user_id);
        //get role credentials
        foreach($user_roles as $user_role) {
            $role = Doctrine::getTable("SysRoles")->getRoleById($user_role->getRoleId()) ;
            $role_privs = Doctrine::getTable("SysRolePriv")->getRolePriv($user_role->getRoleId());
            foreach($role_privs as $role_priv) {
                //取程序名称和权限等
                $progs = Doctrine::getTable("SysProgs")->getProgById($role_priv->getProgId());
                foreach($progs as $prog) {
                    //分解权限
                    //echo $role_priv->getProgPriv();
                    foreach(array(1,2,4,8) as $x) {
                        if(($role_priv->getProgPriv() & $x) <> 0) {
                            $credentials[] = $prog->getProgCode(). "_" . $x;
                        }
                    }
                    
                }
            }
        }
        return $credentials;

    }


}
